import serial
import serial.tools.list_ports

def list_serial_ports():
    """列出当前系统中的所有可用串口"""
    ports = serial.tools.list_ports.comports()
    available_ports = []
    for port, desc, hwid in sorted(ports):
        print(f"{port}: {desc} [{hwid}]")
        available_ports.append(port.device)
    return available_ports

def open_serial_port(port_name, baud_rate=9600):
    """打开指定的串口"""
    try:
        ser = serial.Serial(port_name, baud_rate, timeout=1)
        print(f"串口 {port_name} 已打开，波特率 {baud_rate}")
        return ser
    except serial.SerialException as e:
        print(f"打开串口时出错: {e}")
        return None

def send_data(ser, data):
    """通过打开的串口发送数据"""
    if ser:
        ser.write(data.encode('utf-8'))
        print(f"已发送数据: {data}")

def main():
    print("正在搜索可用的串口...")
    ports = list_serial_ports()
    if not ports:
        print("未找到任何可用的串口。")
        return

    port_name = input("请输入您想使用的串口号 (例如 /dev/ttyUSB0): ")
    if port_name not in ports:
        print("选择的串口无效。")
        return

    baud_rate = input("请输入波特率 (默认 9600): ")
    baud_rate = int(baud_rate) if baud_rate else 9600

    ser = open_serial_port(port_name, baud_rate)
    if ser:
        data_to_send = input("请输入要发送的数据: ")
        send_data(ser, data_to_send)
        ser.close()
        print(f"串口 {port_name} 已关闭。")

if __name__ == '__main__':
    main()
